package com.pricl.biz;

import java.util.List;
import java.util.Map;

import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.pricl.api.util.AdminUserUtils;
import com.pricl.biz.admin.dao.AdminModelDao;
import com.pricl.biz.admin.dao.AdminRoleDao;
import com.pricl.biz.admin.dao.AdminUserDao;
import com.pricl.biz.admin.entity.AdminModel;
import com.pricl.biz.admin.entity.AdminUser;
import com.pricl.biz.admin.entity.criteria.AdminModelCriteria;
import com.pricl.biz.admin.entity.criteria.AdminUserCriteria;
import com.pricl.frame.core.App;
import com.pricl.frame.core.User;
import com.pricl.frame.shiro.AuthorizationInfoHolder;

public class MyApp extends App {

	Logger logger = LoggerFactory.getLogger(MyApp.class);

	@Autowired
	AdminUserDao userDao;

	@Autowired
	AdminRoleDao roleDao;

	@Autowired
	AdminModelDao modelDao;

	@Override
	public void setPrefixPerms(Map<String, String> perms) {
		// perms.put("/static/**", "anon");
		// perms.put("/login*", "anon");
		// perms.put("/logout*", "logout");
	}

	@Override
	public void setSuffixPerms(Map<String, String> perms) {
		perms.put("/**", "authc");
		// perms.put("/**", "anon");
	}

	@Override
	public Map<String, String> getDefinePerms() {
		// List<AppModule> modules = moduleDao.findAll();
		// if (modules != null && !modules.isEmpty()) {
		// Map<String, String> map = new HashMap<String, String>();
		// for (AppModule item : modules) {
		// String shiroUrl = item.getShiroUrl();
		// if (shiroUrl == null || "".equals(shiroUrl.trim())) {
		// continue;
		// }
		// map.put(item.getShiroUrl(), item.getRequestPermission());
		// }
		// return map;
		// }
		return null;
	}

	// TODO 盐的处理
	@Override
	public User findForLogin(String username, String password, String salt) {
		
		// modify by winton 2017-8-21 采用加密机制去查询。
		AdminUserCriteria criteria = new AdminUserCriteria();
		criteria.setUsernameEqualTo(username);
		criteria.setTypeEqualTo(1);
		List<AdminUser> users = userDao.selectByEntity(criteria);
		if (users != null && users.size() == 1) {
			String encryptPassword = AdminUserUtils.INSTANCE.MD5(users.get(0).getSalt() + password);
			if (encryptPassword.equals(users.get(0).getPassword())) {
				if (!users.get(0).getEnabled()) {
					throw new LockedAccountException();
				}
				MyUser myUser = new MyUser();
				myUser.id = users.get(0).getId();
				myUser.name = users.get(0).getUsername();
				myUser.username = users.get(0).getUsername();
				myUser.password = users.get(0).getPassword();
				myUser.salt = users.get(0).getSalt();
				// 用户类型
				myUser.userType = users.get(0).getType();
				
				return myUser;
			}
		}
		return null;
		
		/*AdminUser user = userDao.findByUsernameAndPassword(username, password);
		// System.out.println("findForLogin"+(user != null));
		if (user != null) {
			if (!user.getEnabled()) {
				throw new LockedAccountException();
			}
			MyUser myUser = new MyUser();
			myUser.id = user.getId();
			myUser.name = user.getUsername();
			myUser.username = user.getUsername();
			myUser.password = user.getPassword();
			myUser.salt = user.getSalt();
			// 用户类型
			myUser.userType = user.getType();
			
			return myUser;
		}
		return null;
		 */
	}

	@Override
	public SimpleAuthorizationInfo getInfo(Long key) {
		if (key == null || key.equals("")) {
			return null;
		}
		SimpleAuthorizationInfo authorizationInfo = AuthorizationInfoHolder.get(key);
		if (authorizationInfo == null) {
			authorizationInfo = new SimpleAuthorizationInfo();

			// 用户权限
			List<AdminModel> perms = modelDao.selectByEntity(new AdminModelCriteria());
			if (!perms.isEmpty()) {
				for (AdminModel item : perms) {
					String permStr = parsePermStr(item.getPermCode());
					if (permStr != null)
						authorizationInfo.addStringPermission(permStr);
				}
			}

			// 用户角色权限，优先级高于一般权限
			AdminUser adminUser = userDao.selectByPrimaryKey(key);
			Integer type = adminUser.getType();
			if (type != null) {
				AuthUserType userType = AuthUserType.getType(type);
				if (userType != null && !"".equals(userType.role)) {
					authorizationInfo.addRole(userType.role);
				}
			}

			AuthorizationInfoHolder.put(key, authorizationInfo);
		}
		return authorizationInfo;
	}

	// TODO 简单处理 这么处理的话缓存应该是无效的
	private String parsePermStr(String s) {
		if (s == null || "".equals(s)) {
			return null;
		}
		int i1 = s.indexOf("[");
		int i2 = s.indexOf("]");
		if (i1 == i2)
			return null;
		return s.substring(i1 + 1, i2);
	}

	// @Override
	// public User packageUser() {
	// Subject currentUser = SecurityUtils.getSubject();
	//
	// ShiroUser shiroUser = (ShiroUser) currentUser.getPrincipal();
	//
	// MyUser myUser = new MyUser();
	// myUser.id = shiroUser.getUid();
	// myUser.name = shiroUser.getName();
	// myUser.username = shiroUser.getUserName();
	// return myUser;
	// }
}
